package zl.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zl.bean.Admin;
import zl.bean.RespBean;
import zl.service.AdminService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/api/common")
public class CommonController extends HttpServlet {

    @Autowired
    private AdminService adminService;
    private Admin admin;

    @GetMapping("/get")
    @ResponseBody
    public RespBean getAdmin(HttpSession session){
        admin = (Admin) session.getAttribute("admin");
        return RespBean.ok("成功~~",admin);
    }

    @PostMapping("/update")
    @ResponseBody
    public RespBean updateAdmin(String newPassword , String oldPassword ,HttpSession session){
        if(oldPassword.equals(admin.getPassword())){
            admin.setPassword(newPassword);
            int i=adminService.updateAdmin(admin);
            if(i==1){
                session.invalidate();
                session.setAttribute("admin", admin);
                return RespBean.ok("修改成功");
            }else{
                return RespBean.error("修改失败");
            }
        }else {
            return RespBean.error("旧密码输入错误");
        }
    }
}
